#获取当前日期和时间
from datetime import datetime
now = datetime.now()
print(now)

#获取指定日期和时间
from datetime import datetime
dt = datetime(2020, 12, 12, 13, 47)
print(dt)

#datetime转换为timestamp
#我们把1970年1月1日 00:00:00 UTC+00:00时区的时刻称为epoch time
#当前时间就是相对于epoch time的秒数，称为timestamp
print(dt.timestamp())

#timestamp转换为datetime
#使用datetime提供的fromtimestamp()方法
t = 1607752020.0
print(datetime.fromtimestamp(t))

#timestamp也可以直接被转换到UTC标准时区的时间
print(datetime.utcfromtimestamp(t))

#str转换为datetime
day = datetime.strptime('2020-12-12 13:47:00', '%Y-%m-%d %H:%M:%S')
print(day)

#datetime转换为str,strftime()
now = datetime.now()
print(now.strftime('%a, %b %d %H:%M'))

#datetime加减,实际上就是把datetime往后或往前计算，得到新的datetime,需要导入timedelta这个类
from datetime import timedelta
now = datetime.now()
print(now + timedelta(hours=10))
print(now - timedelta(days=1,hours=10))
print(now + timedelta(days=10))

#本地时间转换为UTC时间
from datetime import timezone
time_utc_8 = timezone(timedelta(hours=8))
now = datetime.now()
dt = now.replace(tzinfo=time_utc_8)
print(dt)

#时区转换
#通过utcnow()拿到当前的UTC时间，再转换为任意时区的时间
dt_utc = datetime.utcnow().replace(tzinfo=timezone.utc)
print(dt_utc)
#北京时间
dt_bj = dt_utc.astimezone(timezone(timedelta(hours=8)))
print(dt_bj)